import React, { useEffect, useState } from 'react';
import { ApiService } from '../services/api';
import { NodeInfo } from '../types/api';
import { API_CONFIG } from '../config';

interface NodeInfoSectionProps {
  node: keyof typeof API_CONFIG.NODES;
}

export const NodeInfoSection: React.FC<NodeInfoSectionProps> = ({ node }) => {
  const [nodeCount, setNodeCount] = useState<number | null>(null);
  const [cacheTransNumber, setCacheTransNumber] = useState<number | null>(null);
  const [acceptedTransNumber, setAcceptedTransNumber] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const fetchNodeInfo = async () => {
    try {
      setLoading(true);
      setError(null);

      // 获取节点信息相关的数据
      const [nodeCountRes, cacheTransRes, acceptedTransRes] = await Promise.allSettled([
        ApiService.getNodeCount(node),
        ApiService.getCacheTransNumber(node),
        ApiService.getAcceptedTransNumber(node)
      ]);

      // Debug: Log the actual response format
      console.log('NodeInfo - NodeCount Response:', nodeCountRes);
      console.log('NodeInfo - CacheTrans Response:', cacheTransRes);
      console.log('NodeInfo - AcceptedTrans Response:', acceptedTransRes);

      // Handle nodeCount response
      if (nodeCountRes.status === 'fulfilled' && nodeCountRes.value && nodeCountRes.value.result) {
        const result = nodeCountRes.value.result as any;
        setNodeCount(parseInt(String(result.nodes || '0')));
      }
      
      // Handle cacheTrans response
      if (cacheTransRes.status === 'fulfilled' && cacheTransRes.value && cacheTransRes.value.result) {
        const result = cacheTransRes.value.result as any;
        setCacheTransNumber(parseInt(String(result.numberofcache || '0')));
      }
      
      // Handle acceptedTrans response
      if (acceptedTransRes.status === 'fulfilled' && acceptedTransRes.value && acceptedTransRes.value.result) {
        const result = acceptedTransRes.value.result as any;
        setAcceptedTransNumber(parseInt(String(result.acceptedNumber || '0')));
      }

      // 检查是否有任何请求失败
      const errors = [nodeCountRes, cacheTransRes, acceptedTransRes]
        .filter(result => result.status === 'rejected')
        .map(result => (result as PromiseRejectedResult).reason?.message || 'Unknown error');

      if (errors.length > 0) {
        setError(`部分数据获取失败: ${errors.join(', ')}`);
      }
    } catch (err) {
      setError(`获取节点信息失败: ${err instanceof Error ? err.message : '未知错误'}`);
      console.error('Error fetching node info:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchNodeInfo();
  }, [node]);

  if (loading) {
    return <div>加载中...</div>;
  }

  if (error) {
    return (
      <div className="bg-white shadow rounded-lg p-6">
        <h2 className="text-xl font-semibold mb-4">节点信息</h2>
        <div className="text-red-500 bg-red-50 p-4 rounded-md">
          <p className="font-medium">错误:</p>
          <p>{error}</p>
          <button 
            onClick={fetchNodeInfo}
            className="mt-2 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white shadow rounded-lg p-6">
      <h2 className="text-xl font-semibold mb-4">节点信息</h2>
      <div className="space-y-4">
        <div>
          <h3 className="font-medium">节点数量</h3>
          <p>{nodeCount !== null ? nodeCount : 'N/A'}</p>
        </div>
        <div>
          <h3 className="font-medium">缓存交易数量</h3>
          <p>{cacheTransNumber !== null ? cacheTransNumber : 'N/A'}</p>
        </div>
        <div>
          <h3 className="font-medium">已接受交易数量</h3>
          <p>{acceptedTransNumber !== null ? acceptedTransNumber : 'N/A'}</p>
        </div>
      </div>
    </div>
  );
}; 